﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tao.OpenGl;
using PocketEngine.Cameras;
using PocketEngine.Images;
using PocketEngine.Maps;
using PocketEngine.Rendering;
using PocketEngine.Engine;
using PocketEngine.Materials;
using PocketEngine.Lights;
using PocketEngine.Effects;
namespace PocketEngine.Batches
{
    public class pRenderBatchItem : pBatchItem
    {
        public pEffect Effect;
        public List<pLight> Lights;
        public pAnimImage Item = null;
        public pDrawParameters Info = null;
        public pRenderBatchItem(pAnimImage item, pDrawParameters pars,List<pLight>lights,pEffect fx)
        {
            Item = item;
            Info = pars;
            Lights = lights;
            Effect = fx;
        }
        public override bool Execute()
        {
            pEffect fx = Effect;

            Gl.glEnable(Gl.GL_BLEND);
            Gl.glBlendFunc(Gl.GL_SRC_ALPHA, Gl.GL_ONE_MINUS_SRC_ALPHA);
            Info.Material.DiffuseMapping = true;
            if (Item.Images[0].Normals != null)
            {
                Info.Material.NormalMapping = true;
            }
            else
            {
                Info.Material.NormalMapping = false;
            }
            if (Item.Images[0].Speculars != null)
            {
                Info.Material.SpecularMapping = true;
            }

            foreach (var l in Lights)
            {
                l.Activate();
                l.ShadowMap.Bind(3);
                if (l.ShadowMap != null && Info.TakeShadow)
                {
                    Info.Material.ShadowMapping = true;
                }
                else
                {
                    Info.Material.ShadowMapping = false;
                }
                fx.Bind(Info.Material);
                if (Info.Material.ShadowMapping) l.ShadowMap.Bind(3);
                if (Info.Material.NormalMapping) Item.Images[0].Normals.Bind(1);
                if (Info.Material.SpecularMapping) Item.Images[0].Speculars.Bind(2);
                pEngine.Pen.TransformedImageShadowMapping((int)Info.X, (int)Info.Y, (int)Info.Width, (int)Info.Height, Item.Images[0], pColor.White, Info.Rotation, Info.Scale);
                if (Info.Material.ShadowMapping) l.ShadowMap.Unbind(3);
                if (Info.Material.NormalMapping) Item.Images[0].Normals.Unbind(1);
                if (Info.Material.SpecularMapping) Item.Images[0].Speculars.Unbind(2);
               fx.Unbind(Info.Material);


                Gl.glBlendFunc(Gl.GL_ONE, Gl.GL_ONE);
            }
            return true;
        }
    }
    public class pDrawParameters
    {
        public float X, Y, Z;
        public float Rotation;
        public float Scale;
        public int Width, Height;
        public pMaterial Material;
        public bool TakeShadow;
    }
}
